<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Common\Common;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
use App\Models\SuningApiLog;
use Exception;
use App\Models\Order;

class SuningController extends Controller
{
    /**
     * 提示方法错误
     */
    function tip(Request $request) {
        return response()->json([
            'result' => 'Y',
            'message' => 'The GET method is not supported！',
        ]);
    }


    // 测试苏宁主动接口
    function test(Request $request)
    {
        return response()->json([
            'result' => 'N',
            'message' => 'http body has json error!',
        ]);

        $reqBody = '{"srvOrder":"9141307223","statusCodeDes":"服务取消","qualityMarkDesc":"保外","arrivalStatus":"E0008","consignee":"陈圣文","arrivalStatusDes":"服务取消","salesOrder":"MP046093542455411501","mobPhoneNum":"13311180918","srvAddress":"7;北京市;北京市;朝阳区;双井街道;;;;华腾大叔啊2508","vendorCode":"71336762","qualityMark":"1","noCompleReason":"服务订单错误","statusCode":"E0008","srvTime":"20201229080000"}';
        $reqData = json_decode($reqBody, true);
        if (!$reqData || json_last_error() != JSON_ERROR_NONE) {
            return response()->json([
                'result' => 'N',
                'message' => 'http body has json error!',
            ]);
        }

        if (!$reqData['salesOrder']) {
            return [
                'result' => 'N',
                'message' => '没有订单号',
            ];
        }
        $order = Order::where('provider_order_id', $reqData['salesOrder'])->first();

        if (!$order) {
            return [
                'result' => 'N',
                'message' => '订单号不存在'. $reqData['salesOrder'],
            ];
        }

        // Log::info($order->id ."\t". $order->provider_order_status ."\t". $reqData['statusCode']);
        try {
            $order->status = Order::formatStatusCode($reqData['statusCode']);
            $order->provider_order_status = $reqData['statusCode'];
            $order->save();

            return [
                'result' => 'Y',
                'message' => '成功' . $order->status,
            ];
        } catch(Exception $e) {
            return [
                'result' => 'N',
                'message' => '数据库操作失败',
            ];
        }
    }

    //和苏宁帮客对接的被动接口
    function index(Request $request)
    {
        $musts = [
            'method', 'app_key', 'sign',
        ];
        $inputs = $request->only($musts);
        if (!$request->has($musts)) {
            return response()->json([
                'result' => 'N',
                'message' => 'some parameters is null!',
            ]);
        }
        $reqBody = $request->getContent();
        Log::info($reqBody);
        $reqData = json_decode($reqBody, true);
        if (!$reqData || json_last_error() != JSON_ERROR_NONE) {
            return response()->json([
                'result' => 'N',
                'message' => 'http body has json error!',
            ]);
        }
  
        $compareSing = Common::SuningSign($inputs['method'], $reqBody, config('app.suning.app_key'), config('app.suning.app_secret'));
        if ($compareSing != $inputs['sign']) {
            return response()->json([
                'result' => 'N',
                'message' => 'sign error!',
            ]);
        }

        switch ($inputs['method']) {
            case "suning.lb.orderstatus.send":
                $returnJson = $this->suningLbOrderstatusSend($reqData);
                break;
            case 'suning.lb.message.send':
                $returnJson = $this->suningLbMessageSend($reqData);
            break;
            default:
                $returnJson = [
                    'result' => 'N',
                    'message' => $inputs['method'] . ' is error!',
                ];
        }

        SuningApiLog::create([
            'from' => 'Suning',
            'req_url' => '',
            'req_method' => 'POST',
            'req_param' => json_encode($inputs),
            'req_body' => $reqBody,
            'resp_status' => 200,
            'resp_body' => json_encode($returnJson)
        ]);
        return response()->json($returnJson);
    }

    /**
     * 苏宁订单状态ASMP通知欢网
     * 
     * {"srvOrder":"9141307223","statusCodeDes":"服务取消","qualityMarkDesc":"保外","arrivalStatus":"E0008","consignee":"陈圣文","arrivalStatusDes":"服务取消","salesOrder":"MP046093542455411501","mobPhoneNum":"13311180918","srvAddress":"7;北京市;北京市;朝阳区;双井街道;;;;华腾大叔啊2508","vendorCode":"71336762","qualityMark":"1","noCompleReason":"服务订单错误","statusCode":"E0008","srvTime":"20201229080000"}
     */
    public function suningLbOrderstatusSend($reqData)
    {
        if (!$reqData['salesOrder']) {
            return [
                'result' => 'N',
                'message' => '没有订单号',
            ];
        }
        $order = Order::where('provider_order_id', $reqData['salesOrder'])->first();
        if (!$order) {
            return [
                'result' => 'N',
                'message' => '订单号不存在',
            ];
        }

        try {
            $order->status = Order::formatStatusCode($order, $reqData['statusCode']);
            $order->provider_order_status = $reqData['statusCode'];

            $order->save();
            return [
                'result' => 'Y',
                'message' => '成功',
            ];
        } catch(Exception $e) {
            return [
                'result' => 'N',
                'message' => '数据库操作失败',
            ];
        }
        
    }

    /**
     * 网点留言通知直连商户
     */
    public function suningLbMessageSend($reqData)
    {
        return [
            'result' => 'Y',
            'message' => 'suningLbMessageSend',
        ];
    }
}
